package com.cash.channel.svc.service.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cash.channel.api.constant.Constant;
import com.cash.channel.api.model.ApiRequestModel;
import com.cash.channel.api.model.ApiResponseModel;
import com.cash.channel.api.model.repay.WdOrderInfoModel;
import com.cash.channel.api.model.request.RepaySubmitRequest;
import com.cash.channel.api.model.response.RepaySubmitResponse;
import com.cash.channel.api.model.user.ThirdIdModel;
import com.cash.channel.svc.dao.ThirdIdMappingMapper;
import com.cash.channel.svc.logic.RepayLogic;
import com.cash.channel.svc.service.base.RepaySubmit;
import com.cash.id.IDGen;
import com.cash.user.model.UserInfoModel;
import com.cash.user.service.UserService;
import geex.core.service.LoanService;
import geex.core.service.SystemService;
import geex.core.service.model.loan.Loan;
import geex.core.service.model.loan.RepayPlan;
import geex.core.service.model.repay.TryCalculateRepayAllResult;
import geex.trans.enums.RepayOnLineTypeEnum;
import geex.trans.req.DeductAmountByCardReq;
import geex.trans.rsp.DeductAmountByCardRsp;
import geex.trans.service.TransDeductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service(Constant.CHANNEL.COMMON + Constant.SERVICE.普通还款)
public class CommonRepaySubmit implements RepaySubmit {

    @Autowired
    private ThirdIdMappingMapper thirdIdMappingMapper;

    @Autowired
    private RepayLogic repayLogic;

    @Autowired
    private LoanService loanService;

    @Autowired
    private UserService userService;

    @Autowired
    private TransDeductService transDeductService;

    @Resource
    private IDGen idGen;

    @Autowired(required = false)
    private SystemService systemService;

    @Override
    public ApiResponseModel<RepaySubmitResponse> doRepaySubmit(ApiRequestModel apiRequestModel) {
        RepaySubmitRequest repaySubmitRequest = JSON.parseObject(apiRequestModel.getData(), RepaySubmitRequest.class);
        if (StringUtils.isEmpty(repaySubmitRequest.getOrderNo())) {
            return new ApiResponseModel<>(false,0,"订单号不能为空",null);
        }

        Integer period = 0;
        if(!Constant.payType.提前结清.equals(repaySubmitRequest.getPayType())){
            if (repaySubmitRequest.getPeriod()==null) {
                return new ApiResponseModel<>(false,0,"期数不能为空",null);
            }
            period = Integer.valueOf(repaySubmitRequest.getPeriod());
        }

        String orderNo = repaySubmitRequest.getOrderNo();

        ThirdIdModel thirdIdModel= thirdIdMappingMapper.getThirdIdByThirdIdAndChannel(orderNo, apiRequestModel.getChannel());

        if (thirdIdModel == null || StringUtils.isEmpty(thirdIdModel.getCUserUid())) {
            return new ApiResponseModel<>(false,0,"未找到用户信息",null);
        }
        if (StringUtils.isEmpty(repaySubmitRequest.getWithdrawId())) {
            return new ApiResponseModel<>(false,0,"未找到提现订单号",null);
        }

        WdOrderInfoModel wdOrderInfoModel = this.repayLogic.findWithdrawAppInfoByAppId(repaySubmitRequest.getWithdrawId());
        if (wdOrderInfoModel == null || StringUtils.isEmpty(wdOrderInfoModel.getCWdAppId())) {
            return new ApiResponseModel<>(false,0,"未找到提现订单信息",null);
        }
        log.info("查询新核心还款明细：{}" , wdOrderInfoModel.getCWdAppId());
        Loan loan = loanService.findLoanByExtId(wdOrderInfoModel.getCWdAppId());
        List<RepayPlan> repayPlanList = loan.getRepayPlanList();
        log.info("查询CWdAppId:{}核心还款明细结果{}：",wdOrderInfoModel.getCWdAppId() , repayPlanList);
        if (Constant.payType.正常还款==repaySubmitRequest.getPayType()) {
            if ((repayPlanList == null||repayPlanList.size() == 0 || period > repayPlanList.size() || period < 1)) {
                return new ApiResponseModel<>(false,0,"期数不正确",null);
            }
            RepayPlan repayPlan=repayPlanList.get(period-1);
            if (repayPlan == null) {
                return new ApiResponseModel<>(false,0,"未查询到该期还款计划",null);
            }
            if (repayPlan.getFinishDate()!=null) {
                return new ApiResponseModel<>(false,0,"该期账单已还",null);
            }
        }

        DeductAmountByCardReq deductAmountByCardReq = new DeductAmountByCardReq();
        RepayOnLineTypeEnum repayType = RepayOnLineTypeEnum.STANDARD;
        if(Constant.payType.提前结清==repaySubmitRequest.getPayType()){
            repayType = RepayOnLineTypeEnum .PRE_DEDUCT;
            TryCalculateRepayAllResult res = loanService.tryCalculateRepayAll(loan.getLoanNo(), systemService.getSystemDate());
            log.info("提前结清试算 tryCalculateRepayAll  res:" + net.sf.json.JSONObject.fromObject(res));
            if(!res.isSuccess()){
                return new ApiResponseModel<>(false ,-1, res.getErrorMessage(), null);
            }
            deductAmountByCardReq.setAmount(res.getAmount());
        }

        UserInfoModel userInfoModel = userService.findUserInfoByUid(thirdIdModel.getCUserUid());
        String extId = String.valueOf(idGen.nextId());
        deductAmountByCardReq.setExtId(extId);

        deductAmountByCardReq.setIdNo(userInfoModel.getcIdno());
        deductAmountByCardReq.setAppId(repaySubmitRequest.getWithdrawId());
        deductAmountByCardReq.setName(userInfoModel.getcName());
        deductAmountByCardReq.setRepayType(repayType);
        log.info("资金端：扣款接口开始：" + deductAmountByCardReq);
        DeductAmountByCardRsp deductAmountByCardRsp = transDeductService.deductAmountByLoan(deductAmountByCardReq);
        log.info("资金端：扣款接口完成：" + deductAmountByCardRsp);
        if(!deductAmountByCardRsp.isSuccess()){
            return new ApiResponseModel<>(false ,-1, deductAmountByCardRsp.getErrorMessage(), null);
        }
        return new ApiResponseModel<>(true,0,"",new RepaySubmitResponse(extId));
    }
}
